package com.example.hao.flowercityfm.Files;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.util.Log;


import com.example.hao.flowercityfm.application.MyApp;

import java.io.BufferedReader;
import java.io.BufferedWriter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import static android.content.Context.MODE_PRIVATE;


public class Cache {

    private Context context;

    public static final String FM_DATA = "FMData";

    public Cache(Context context) {
        this.context = context;
    }

    /* 检查外部存储器是否可用来读取和写入 */
    private boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    /* 检查外部存储是否至少可以读取 */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }

    private String getExterCacheDir() {
        if (isExternalStorageWritable()) {
//路径:SD卡的共有的根目录/Android/data/应用程序包名/cache
            return context.getExternalCacheDir().getName();
        }
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void writeFile(String fileName, String json) {
        File file = new File(getExterCacheDir(), fileName);
        Log.d(MyApp.TAG, "writeFile: " + file.getAbsolutePath());
        try (FileOutputStream fos = context.openFileOutput(file.getName(), MODE_PRIVATE);
             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos))) {
            bw.write(json);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public String readFile(String fileName) {

        try (FileInputStream fis = context.openFileInput(fileName);
             BufferedReader br = new BufferedReader(new InputStreamReader(fis));) {
            return br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
